commonly, we remove rows from the database when deleting records from the site.
But laravel introduces SoftDeletes
in models that way we can't remove it from the database but if remove the record from the front side then it doesn't show the record on the front. So we can retrieve records from the database if we remove the wrong row.
How to work soft delete,
laravel add deleted_at column on the table that is default will be null and when we remove then it will place current timestamp,
Laravel Model always fetches that record has only deleted_at = null.
So, how to use in our project, so first when you create table migration then you have to add softDeletes(). you can see as bellow example of migration.
Migration Example:
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBlogsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('blogs', function(Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("blogs");
} }
Ok, now you can find the deleted_at column in your items table and you have also model that should look like as bellow:
namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Item extends Model { use SoftDeletes; public $fillable = ['title','description']; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; }
Now, you can use the Item model as normally as you use before, you get all records like this way.
$data = Item::get();
It will return all records that has deleted_at = null only and you can also remove records like this way:
$data = Item::find(1)->delete();
You can check and use it
We are Recommending you:
- Laravel 8/7 Overwriting the Default Pagination System
- Laravel 8 .htaccess file for php 8
- How to Secure Your Laravel App: Beyond SSL Basics
- Laravel 8 multi auth login
- Integrate Zoho SMTP Mail Configurations in Laravel?
- Why Use the Repository Pattern in a Laravel Application
- How to generate dynamic real time sitemap.xml file in Laravel 8
- How to change timezone in laravel 8
- How to create real time sitemap.xml file in Laravel
IntroductionGoogle Search Console (GSC) is a...
Master Your Time with the 80/20 Rule: A...
Get Control of Your Time: 6 Easy Ways...
India’s startup space is booming in 2025....
Using the right words in an interview can...
India’s startup space is booming in 2025....
Git is like a superhero for coders—it...
these are following steps to remove...
we provide custom social share links for...